package cn.stylefeng.guns.modular.business.custom.handler;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.Arrays;

/**
 * @Description: Integer数组 转字符串存入数据库
 * @Author jzy
 * @Date 2020/9/23 0023
 **/
@MappedTypes({Integer[].class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        if (integers == null) {
            preparedStatement.setNull(i, Types.VARCHAR);
        } else {
            JSONArray jsonArray = new JSONArray(Arrays.asList(integers));
            preparedStatement.setString(i, jsonArray.toString());
        }
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, String s) throws SQLException {
        String columnValue = resultSet.getString(s);
        return this.getIntegerArray(columnValue);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {
        String columnValue = resultSet.getString(i);
        return this.getIntegerArray(columnValue);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String columnValue = callableStatement.getString(i);
        return this.getIntegerArray(columnValue);
    }

    private Integer[] getIntegerArray(String columnValue) {

        if (StringUtils.isBlank(columnValue))
            return null;
        JSONArray jsonArr = JSONArray.parseArray(columnValue);

        return  jsonArr.toArray(new Integer[jsonArr.size()]);
    }
}
